package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.FreeMarkService;
import com.heima.file.service.MinioTemplate;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.FileWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class FreeMarkServiceImpl implements FreeMarkService {

    @Autowired
    private Configuration configuration;
    @Autowired
    private MinioTemplate minioTemplate;
    @Autowired
    private ApArticleService apArticleService;

    @Async("taskExecutor")
    @Override
    public void createHtml(ApArticle apArticle, String content) {
        log.info("子线程，创建静态页面！");
        try {
//        获取模板对象
            Template template = configuration.getTemplate("article.ftl");
//        准备静态页的数据
            Map<String,Object> map = new HashMap<>();
            map.put("content", JSONArray.parseArray(content));
//        生成静态页面
            StringWriter stringWriter = new StringWriter();
            template.process(map,stringWriter);
//        获取输入流，存入Minio，返回页面的url
            ByteArrayInputStream inputStream = new ByteArrayInputStream(
                    stringWriter.toString().getBytes()
            );
            String fileName = apArticle.getId()+".html";
            String url = minioTemplate.uploadHtmlFile(fileName, inputStream);
//        把url保存到article表
            if(StringUtils.isNotBlank(url)){
//                更新到article表
                ApArticle apArticle1 = new ApArticle();
                apArticle1.setId(apArticle.getId());
                apArticle1.setStaticUrl(url);
                apArticleService.updateById(apArticle1);
            }
        }catch (Exception e){
            log.error("生成静态页异常！");
            e.printStackTrace();
        }
    }
}
